/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.mem.impl.ram;

import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;

import java.io.IOException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.sabayframework.mem.BigBuffer;
import org.sabayframework.mem.IdGenerator;
import org.sabayframework.mem.Transaction;
import org.sabayframework.mem.Transaction.Locking;
import org.sabayframework.mem.impl.AbstractSpace;
import org.sabayframework.mem.impl.BigBufferAllocator;
import org.sabayframework.mem.impl.MergingBigBufferAllocator;
import org.sabayframework.mem.impl.SequentialIdGenerator;
import org.sabayframework.mem.impl.TransactionImpl;
import org.sabayframework.queue.ExecutionQueue;

/**
 * Implementation of Space that keeps all data in off-heap memory.
 * @author Alex Antonau
 * */
public class RAMSpace extends AbstractSpace {

	final BigBufferAllocator allocator;
	final Long2ObjectOpenHashMap<Version> records = new Long2ObjectOpenHashMap<Version>();		
    final ReadWriteLock lock = new ReentrantReadWriteLock();
	final static class Version{
		long lastModified;
		long locked;
		BigBuffer data;
	}
	/**
	 * 
     * @param totalSize total size of the RAM space.
     * @param executionQueue execution queue to use for transactions
	 * */
	public RAMSpace(final int totalSize, ExecutionQueue executionQueue) {
		this(new MergingBigBufferAllocator(totalSize),new SequentialIdGenerator(0) ,executionQueue);
	}

	public RAMSpace(BigBufferAllocator allocator, IdGenerator idGenerator, ExecutionQueue executionQueue) {
		super(idGenerator, executionQueue);
		this.allocator = allocator;
	}

	@Override
	public Transaction beginTransaction(Locking locking) {
		if(isClosed()) throw new IllegalStateException("Space is closed");
		final TransactionImpl t = new TransactionImpl(
				getIdGenerator().getNextId(), 
				getExecutionQueue());
		switch (locking) {
		case NONE:
			t.submitProcessingActivity(new NoLockTxActivity(this, t));
			break;
		case OPTIMISTIC:
			t.submitProcessingActivity(new OptimisticTxActivity(this, t));
			break;
		case PESSIMISTIC:
			t.submitProcessingActivity(new PessimisticTxActivity(this, t));
			break;
		default:
			throw new IllegalArgumentException("Unsupported locking: "+locking);
		}
		started(t);
		return t;
	}

	@Override
	public void close() throws IOException {
		lock.writeLock().lock();
		try{
			super.close();
			allocator.close();
			records.clear();
		} finally{
			lock.writeLock().unlock();
		}
	}
	
}
